<?php
namespace app\gr\controller;

use app\common\wechat\Wxauth;
use app\gr\BLL\CardPubBLL;
use app\gr\BLL\CardRedeemBLL;
use cmf\controller\HomeBaseController;

class CardPubController extends HomeBaseController
{
    private $bll;
    private $ControlName = "CardPub";

    public function __construct(CardPubBLL $cardPub)
    {
        parent::__construct();
        $this->bll = $cardPub;
    }

    public function index()
    {
        // return $this->fetch('cant');
        return $this->fetch();
    }

    public function check()
    {
        if ($this->request->isPost()) {
            $no       = input('no');
            $psd      = input('psd');
            $cardInfo = $this->bll->getByField('card_no', $no);

            if ($cardInfo) {
                if ($cardInfo['status'] == 1 && $cardInfo['card_psd'] == $psd) {
                    $state = $cardInfo['id'] . '^' . $no . '^' . $psd;
                    $this->success('验证成功', url("$this->ControlName/redeem", array('state' => $state)));
                }
            }
            $this->error('验证失败');

        }
    }

    public function redeem()
    {
        //验证页面传过来的参数
        $state = input('state');
        //获取openid
        if (config('is_server')) {
            $auth   = new Wxauth(config('wechat'), 'base', $state);
            $openid = $auth->openid;
        } else {
            $openid = "a123458";
        }
        //id，no,psd
        $parameter = explode("^", $state);
        //查询图片
        $info = $this->bll->with('cardType')->getbyid($parameter[0]);

        $this->assign('openid', $openid);
        $this->assign('parameter', $parameter);
        $this->assign('img', $info['img']);
        return $this->fetch();
    }

    public function redeemPost()
    {
        if ($this->request->isPost()) {
            $data   = $this->request->param();
            $result = $this->validate($data, "CardRedeem");
            if ($result !== true) {
                $this->error($result);
            }
            $cardRedeemBLL = new CardRedeemBLL();
            if ($cardRedeemBLL->create($data)) {
                $this->success('新增成功', url("CardRedeem/index"));
            } else {
                $this->error("添加失败！");
            }

        }
    }
}
